<template>
  <div>
    <!-- sku展示 -->
    <nut-popup :closeable="true" position="bottom" round :custom-style="{ height: '800rpx' }" v-model:visible="show">
      <div p-36rpx h-600rpx overflow-scroll>
        <!-- 商品 -->
        <div flex flex-a-c>
          <div>
            <image w-200rpx h-200rpx :src="props.goods.thumbnail" />
          </div>
          <div ml-10rpx>
            <div text-main-color font-bold text-42rpx>
              <!-- 促销价格 -->
              <span v-if="props.info.data.promotionPrice">
                {{ unitPrice(props.info.data.promotionPrice, '￥') }}
              </span>
              <span v-else>
                {{ unitPrice(props.goods.price, '￥') }}
              </span>
            </div>
            <div line-through v-if="props.info.data.promotionPrice" color-warmGray>
              {{ unitPrice(props.info.data.price, '￥') }}
            </div>
            <div mt-20rpx>
              <!-- 规格 -->
              <div text-24rpx>
                已选
              </div>
              <!-- 库存 -->
              <div text-24rpx>
                库存 <span>{{ props.goods.quantity }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 规格 -->
        <div class="goods-sku-view" :key="specIndex" v-for="(spec, specIndex) in goodsSkuList">
          <div class="sku-view-list">
            <div class="view-class-title" my-20rpx>{{ spec.name }}</div>
            <!-- 正常逻辑 循环出sku -->
            <div v-if="!parentOrder"
              :class="spec_val.value == choiceSkuList[specIndex] ? ['text-main-color', 'bg-main-color-10', 'active', 'border-main-color'] : 'default'"
              class="sku-view-item" v-for="(spec_val, spec_index) in spec.values" :key="spec_index"
              @click="handleClickSpec(spec, specIndex, spec_val)">
              {{ spec_val.value }}
            </div>
            <!-- {{ spec.values }} -->
            <!-- 拼团购买，仅筛选出当前拼团类型商品 -->
            <div v-if="parentOrder"
              :class="spec_val.value == choiceSkuList[specIndex] ? ['text-main-color', 'bg-main-color-10', 'active', 'border-main-color'] : 'default'"
              class="sku-view-item" v-for="(spec_val, spec_index) in spec.values" :key="spec_index"
              @click="handleClickSpec(spec, specIndex, spec_val)">
              {{ spec_val.value }}
            </div>
          </div>
        </div>
        <!-- 数量 -->
        <div mt-20rpx flex flex-a-c flex-j-sb>
          <div>
            数量
          </div>
          <nut-input-number v-model="num" />
        </div>
      </div>
      <div position-fixed flex gap-24rpx flex-a-c bottom-0 left-0 right-0 p-36rpx>
        <div flex-1 v-if="isShowCartList"> <nut-button block type="primary" @click="bill()">加入购物车</nut-button></div>
        <div flex-1> <nut-button block type="warning" @click="bill('BUY_NOW')">立即购买</nut-button></div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup lang="ts">

import { unitPrice } from '@/utils/filters';
const show = ref<boolean>(false)
const num = ref<number>(1)

const goodsSkuList = ref<any>([]) //商品规格
const choiceSkuList = ref<any>([])
const choiceName = ref<any>('') //选中商品的昵称
const selected = ref<any>('') //选中商铺sku,
const parentOrder = ref<any>(false) //父级拼团活动的数据 - 如果是团员则有数据
interface Goods {
  thumbnail: string,
  quantity: number,
  price: number,
  skuId: number,
  goodsId: number,
  specs: any, //规格商品详情中 specs 字段全部传入
  [key: string]: any
}
const whoami = ref<any>('')
const emit = defineEmits(['click', 'bill'])
const props = defineProps<{
  goods: Goods
  salesModel: string // 销售模式
  info?: any //整个商品对象

}>()

const isShowCartList = computed(() => {
  console.log('props.info.data.___promotion', props.info.data.___promotion)
  return props.info.data.goodsType !== 'VIRTUAL_GOODS' && props.info.data.___promotion !== 'pintuan'
})
const ids = ref<any>({
  goodsId: props.goods.goodsId,
  skuId: props.goods.skuId
})
watch(() => props.goods, (val) => {
  init(val)
}, { deep: true, immediate: true })

function open() {
  // 如果说给open这个方法传值了，就说明不是自己购买
  show.value = true
}

// 回调商品信息
function bill(val?: string) {

  let type = val
  if (props.info.data.goodsType === 'VIRTUAL_GOODS') {
    type = 'VIRTUAL'
  }
  if (props.info.data.___promotion === 'pintuan') {
    type = 'PINTUAN'
  }



  emit('bill', {
    skuId: ids.value.skuId,
    goodsId: props.goods.goodsId,
    type: type,
    num: num.value,
    _self: whoami.value
  })
  show.value = false
}

// 点击规格
function handleClickSpec(val: any, index: number, specValue: any) {
  choiceSkuList.value[index] = specValue.value;
  let selectedSkuId = props.goods.specs.find((i: any) => {
    let matched = true;
    let specValues = i.specValues.filter((j: any) => j.specName !== 'images');
    for (let n = 0; n < specValues.length; n++) {
      if (specValues[n].specValue !== choiceSkuList.value[n]) {
        matched = false;
        return;
      }
    }
    if (matched) {
      return i;
    }
  });
  if (selectedSkuId?.skuId) {
    choiceSkuList.value[index] = specValue.value;
    selected.value = {
      spec: {
        specName: val.name,
        specValue: specValue.value
      },
      data: props.goods
    };
    choiceName.value = specValue.value;
    ids.value = {
      skuId: selectedSkuId.skuId,
      goodsId: props.goods.goodsId
    }
    emit('click', {
      ...ids.value,
      ...selected.value
    });
  } else {
    uni.showToast({
      title: '暂无该商品!',
      duration: 2000,
      icon: 'none'
    });
  }
}

// 初始化数据
function init(val: any) {
  const list = val.specs
  // 格式化数据
  let arr = [{}];

  if (!Array.isArray(list)) {
    return false;
  }
  list.forEach((item, index) => {
    item.specValues.forEach((spec: any, specIndex: number) => {
      let name = spec.specName;
      let values = {
        value: spec.specValue,
        quantity: item.quantity,
        skuId: item.skuId
      };
      if (name === 'images') {
        return;
      }

      arr.forEach((arrItem: any, arrIndex: number) => {
        if (
          arrItem.name == name &&
          arrItem.values &&
          !arrItem.values.find((i: any) => {
            return i.value === values.value;
          })
        ) {
          arrItem.values.push(values);
        }

        let keys = arr.map((key: any) => {
          return key.name;
        });
        if (!keys.includes(name)) {
          arr.push({
            name: name,
            values: [values]
          });
        }
      });
    });
  });

  arr.shift();
  goodsSkuList.value = arr;

  list.forEach(item => {

    // 默认选中
    if (item.skuId === props.goods.skuId) {
      item.specValues
        .filter((i: any) => i.specName !== 'images')
        .forEach((value: any, _index: number) => {
          choiceSkuList.value[_index] = value.specValue;

          choiceName.value = value.specValue;

          selected.value = {
            spec: value,
            data: props.goods
          };
        });
    }
  });
  emit('click', {
    ...selected.value
  });



}



defineExpose({ open, whoami })

</script>

<style scoped lang="scss">
.active {
  font-weight: bold;
  box-sizing: border-box;
}

.goods-sku-view {

  overflow-y: auto;

  .sku-view-list {
    >.sku-view-item {
      flex: 1;
      padding: 0 36rpx;
      overflow: hidden;
      height: 60rpx;
      line-height: 60rpx;
      float: left;
      text-align: center;
      margin-left: 24rpx;
      margin-bottom: 20rpx;
      font-size: 22rpx;
      border-radius: 30rpx;
      max-width: 640rpx;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.goods-sku-number {
  justify-content: space-between;
  display: flex;

  padding-bottom: 20rpx;

  >.view-class-title {

    flex: 8;
  }

  >.view-class-input {
    flex: 1;
  }
}

.default {

  color: #262626;
  background: #f2f2f2;
}
</style>
